/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
  vector<vector<int>> levelOrder(TreeNode* root) {

    vector<vector<int>> ans;
    queue<TreeNode*> q;

    q.push(root);
    int cnt = 1;
    int nxtCnt = 0;
    vector<int> temp;
    while(!q.empty()){
      TreeNode *p = q.front();

      if(p == nullptr){
        --cnt;
        q.pop();
        continue;
      }

      temp.push_back(p->val);
      if(p->left){
        q.push(p->left);
        ++nxtCnt;
      }
      if(p->right){
        q.push(p->right);
        ++nxtCnt;
      }

      --cnt;
      q.pop();
      if(cnt <= 0){
        cnt = nxtCnt;
        nxtCnt = 0;
        ans.push_back(temp);
        temp.clear();
      }
    }

    return ans;

  }
};